/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.web.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.iwindplus.boot.domain.constant.CommonConstant.TraceConstant;
import com.iwindplus.boot.web.manager.context.ContextTransManager;
import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * OkHttpClient拦截器.
 *
 * @author zengdegui
 * @since 2020/4/23
 */
@Slf4j
public class OkHttpClientInterceptor implements Interceptor {

    @Resource
    private ContextTransManager contextTransManager;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Map<String, String> parameters = this.getStringMap(request);
        final Map<String, String> map = contextTransManager.buildRequestHeaderInMdc(parameters);
        if (MapUtil.isEmpty(map)) {
            return chain.proceed(request);
        }
        Request.Builder builder = request.newBuilder();
        map.entrySet().stream()
            .filter(entry -> ObjectUtil.isNotEmpty(entry.getValue()))
            .forEach(entry -> builder.header(entry.getKey(), entry.getValue()));
        return chain.proceed(builder.build());
    }

    private Map<String, String> getStringMap(Request request) {
        Map<String, String> parameters = new HashMap<>(16);
        final Map<String, List<String>> headers = request.headers().toMultimap();
        if (MapUtil.isEmpty(headers)) {
            return parameters;
        }
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            if (CollUtil.isEmpty(entry.getValue())) {
                continue;
            }
            for (String value : entry.getValue()) {
                parameters.put(entry.getKey(), value);
            }
        }
        if (CharSequenceUtil.isNotBlank(parameters.get(TraceConstant.REAL_IP))) {
            return parameters;
        }
        parameters.put(TraceConstant.REAL_IP, request.url().host());
        return parameters;
    }
}
